<template>
  <div class="action-editor">
    <el-button type="primary" @click="importAction">导入动作</el-button>
    <el-input
      v-model="scriptName"
      placeholder="请输入脚本名称"
      style="margin-top: 20px;width: 20%;"
    ></el-input>
    <div class="visualization-area">
      <p v-if="actions.length">导入的动作坐标:</p>
      <ul>
        <li v-for="(action, index) in actions" :key="index">
          X:{{ action.x }}, Y:{{ action.y }}
        </li>
      </ul>
    </div>
    <el-button type="success" @click="completeEditing">保存</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      actions: [],
      scriptName: ''
    };
  },
  methods: {
    async importAction() {
      try {
        const response = await fetch('/api/script/script/getMousePositions');
        const data = await response.json();
        this.actions = data;
      } catch (error) {
        console.error('导入动作失败:', error);
      }
    },
    async completeEditing() {
      if (!this.scriptName) {
        this.$message.warning('请先输入脚本名称。');
        return;
      }
      try {
        const userName = localStorage.getItem('user_name');
        if (!userName) {
          this.$message.warning('未找到用户信息，请确保用户已登录。');
          return;
        }
        await fetch('/api/script/script/saveActions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ 
            scriptName: this.scriptName, 
            actions: this.actions, 
            userName: userName 
          })
        });
        this.$message.success('编辑完成，动作已保存！');
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败，请重试。');
      }
    }
  }
};
</script>

<style scoped>
.action-editor {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.visualization-area {
  width: 80%;
  height: 300px;
  border: 1px solid #dcdfe6;
  margin: 20px 0;
  position: relative;
  overflow: hidden;
}
.visualization-area p {
  margin: 0;
}
</style>